<template>
  <div class="sy-kyc">
    <div class="main">
      <el-form class="kyc-form" :label-position="labelPosition" ref="form" :model="form">
        <div class="top-tips baseDocument1">
          <img src="../../assets/bussiness/nav_icon.png" alt="" />
          <span>企业营业执照</span>
        </div>

        <el-row class="kyc-row">
          <el-col :span="8">
            <div class="bus-title">营业执照</div>
            <div class="iu-left" v-if="actionType=='1'">
              <img style="width: 100px;height: 100px" :src="!!form.businessLicenseUrl?form.businessLicenseUrl:''"/>
              <p class="yyzz-item"><a @click="showBigImage(form.businessLicenseUrl)">预览</a></p>
            </div>
            <div class="iu-left" v-else>
              <upload ref="yyzzUpload" id="bussinessFile"
                      :imageUrl.sync="form.businessLicenseUrl"
                      v-on:upload-file="yyzzFileUpload"
                      @bigimg="showBigImage"
              >
              </upload>
            </div>
          </el-col>
          <el-col :span="9">
            <el-form-item label-width="140px" prop="tenantName" :rules="vType('','企业名称',true,'blur')" label="企业名称">
              <el-input @focus="clearValidate" placeholder="请输入" disabled
                        v-model="form.tenantName">
              </el-input>
            </el-form-item>
            <el-form-item label-width="140px" prop="uscCode" :rules="vType('uscCode','统一信用代码',true,'blur')"
                          label="统一信用代码">
              <el-input @focus="clearValidate" disabled placeholder="请输入"
                        v-model="form.uscCode">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="top-tips">
          <img src="../../assets/bussiness/nav_icon.png" alt="" />
          <span>法定代表人信息</span>
        </div>

        <el-row class="kyc-row">
          <el-col :span="8">
            <div class="item-upload" style="width: 100%">
              <div class="bus-title">法人身份证</div>
              <div class="iu-left" style="margin-right: 6px">
                <p class="llt-upload">
                  [正面照]
                </p>
                <upload ref="sfzzmUpload" id="cardFile"
                        :imageUrl.sync="form.photoFrontUrl" @bigimg="showBigImage(form.photoFrontUrl)"
                        v-on:upload-file="cardFileUpload">
                </upload>
              </div>
              <div class="iu-left">
                <p class="llt-upload">
                  [反面照]
                </p>
                <upload ref="sfzfmUpload" id="cardReFile"
                        :imageUrl.sync="form.photoBackUrl" @bigimg="showBigImage(form.photoBackUrl)"
                        v-on:upload-file="cardReFileUpload">
                </upload>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="140px" prop="legalPerson" :rules="vType('','法人姓名',true,'blur')" label="法人姓名">
              <el-input @focus="clearValidate" placeholder="请输入法人姓名"
                        v-model="form.legalPerson">
              </el-input>
            </el-form-item>
            <el-form-item label-width="140px" prop="certificateRegistrationDate" :rules="vType('','证件注册日期',true,'change')"
                          label="证件注册日期">
              <el-date-picker value-format="yyyyMMdd" format="yyyy-MM-dd" type="date"
                              v-model="form.certificateRegistrationDate"
                              style="width: 100%;" :picker-options="pickerOptions"></el-date-picker>
            </el-form-item>
            <div style="height: 2px"></div>
            <el-form-item label-width="140px" prop="corporatePhone" :rules="vType('mobile','手机号',true,'blur')" label="手机号">
              <el-input @focus="clearValidate" placeholder="请输入手机号"
                        v-model="form.corporatePhone">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-right: 20px;">
            <el-form-item label-width="140px" prop="identificationNumber" :rules="vType('','证件号码',true,'blur')"
                          label="证件号码">
              <el-input @focus="clearValidate" placeholder="请输入证件号码"
                        v-model="form.identificationNumber">
              </el-input>
            </el-form-item>
            <el-form-item label-width="140px" class="kyc-col" prop="certificateExpirationDate"
                          :rules="vType('','证件到期日',true,'change')" label="证件到期日">
              <div class="top" style="width: 30%;float: left;height: 42px;position: relative;top: -10px;">
                <el-radio v-model="corporateZjType" label="0">长期</el-radio>
                <el-radio v-model="corporateZjType" label="1">固定</el-radio>
              </div>
              <el-date-picker v-show="corporateZjType=='1'" value-format="yyyyMMdd" format="yyyy-MM-dd"
                              style="width:70%;float: left"
                              type="date"
                              v-model="form.certificateExpirationDate"></el-date-picker>
            </el-form-item>
            <!--            <el-form-item prop="photoVerifyCode"
                                      :rules="vType('','验证码',true,'blur')" label="验证码">
                          <el-input style="width: 50%" @focus="clearValidate" placeholder="请输入"
                                    v-model="form.photoVerifyCode" />
                          <timer-legal ref="disabledLegal" class="btn btn-default" v-on:run="sendCode(form.corporatePhone,'disabledLegal')"  v-on:stop="setDisabled(false,'disabledLegal')"
                            :disabled="disabledLegal" :second="60">
                          </timer-legal>
                        </el-form-item>-->
          </el-col>
        </el-row>

        <div class="top-tips">
          <img src="../../assets/bussiness/nav_icon.png" alt="" />
          <span>经办人信息</span>
        </div>

        <el-row class="kyc-row" style="padding-left: 68px;">
          <el-checkbox v-model="sameWithCorp">与法人信息一致</el-checkbox>
        </el-row>

        <el-row class="kyc-row kyc-last">
          <el-col :span="8">
            <el-form-item label-width="140px" prop="contactsIdentificationName" :rules="vType('','姓名',true,'blur')" label="经办人姓名">
              <el-input :disabled="sameWithCorp" @focus="clearValidate" placeholder="请输入"
                        v-model="form.contactsIdentificationName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="140px" prop="contactsIdentificationNumber" :rules="vType('mobile','手机号码',true,'blur')" label="手机号码">
              <el-input :disabled="sameWithCorp" @focus="clearValidate" placeholder="请输入手机号码"
                        v-model="form.contactsIdentificationNumber">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-right: 20px;" v-if="!sameWithCorp">
            <el-form-item label-width="140px" prop="contactsIdentificationVerifyCode"
                          :rules="vType('','验证码',true,'blur')" label="验证码">
              <el-input style="width: 50%" @focus="clearValidate" placeholder="请输入"
                        v-model="form.contactsIdentificationVerifyCode" />
              <timer-contacts ref="disabledContacts" class="btn btn-default" v-on:run="sendCode(form.contactsIdentificationNumber,'disabledContacts')"  v-on:stop="setDisabled(false,'disabledContacts')"
                              :disabled="disabledContacts" :second="60">
              </timer-contacts>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="kyc-row kyc-last">
          <el-col :span="8">
            <el-form-item label-width="140px" prop="contactsIdentificationCard" :rules="vType('','证件号码',true,'blur')"
                          label="证件号码">
              <el-input :disabled="sameWithCorp" @focus="clearValidate" placeholder="请输入证件号码"
                        v-model="form.contactsIdentificationCard">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <div class="top-tips baseDocument1">
          <img src="../../assets/bussiness/nav_icon.png" alt="" />
          <span>其它信息</span>
        </div>
        <el-row class="kyc-row">
          <p style="text-align: left; color: #606266; padding-left: 20px;">企业或企业主本人或企业主配偶是否有一套本地或北京/上海/深圳/杭州/南京/苏州/无锡的商品住宅</p>
          <el-form-item style="padding-left: 50px" label-width="20px" prop="isProperty" :rules="vType('','选择项',true,'change')">
            <el-radio-group v-model="form.isProperty" :disabled="disabledHouse">
              <el-radio style="padding-right: 12px" :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

        <el-row class="kyc-row_last">
          <el-button type="warning" class="kyc-btn" :loading="btnLoading"
                     @click="handleSubmitDown">
            提交
          </el-button>
        </el-row>
      </el-form>
    </div>
    <msg :showMsg="showMsg" @hide="hideMsg">
      <img style="height: 100%;width: 100%" :src="imageUrl"/>
    </msg>

    <e-sign :formObject="form" ref="eSign" :showEsign="showEsign" @closeSign="closeSign" @goSign="submitKycForm(1)"></e-sign>

  </div>
</template>

<script>

import {mapState} from 'vuex';
import upload from '../common/upload';
import {idCardUpload, idCardUploadBack, licenseUpload, modifyUserKyc,isESign,esign} from '@/api/authen/agreed';
import {queryUserKyc} from '@/api/plat/plat';
import {Loading} from 'element-ui';
import Msg from '../../components/common/alert/msg';
import {updateCurrentUser,sendVeriCode} from '@/api/login/login';
import timerLegal from '../common/yzm'
import timerContacts from '../common/yzm'
import eSign from '../common/esign'
export default {
  name: "supplyInfo",
  data() {
    return {
      showEsign: false,
      disabledLegal: false,
      disabledContacts: false,
      sameWithCorp: false,
      btnLoading: false,
      imageUrl: '',
      form: {
        businessLicenseUrl: '',
        certificateExpirationDate: '',
        certificateRegistrationDate: '',
        contactsIdentificationCard: '',
        contactsIdentificationName: '',
        contactsIdentificationNumber: '',
        corporationStep: 'step6',
        identificationNumber: '',
        legalPerson: '',
        photoBackUrl: '',
        photoFrontUrl: '',
        tenantName: '',
        uscCode: '',
        corporatePhone:'',
        photoVerifyCode:'',
        contactsIdentificationVerifyCode:'',
        isProperty:''
      },
      labelPosition: 'right',
      corporateZjType: '',
      cardTypeList: [
        {
          code: 'Ind01',
          name: '身份证'
        }
      ],
      showMsg: false,
      checkXY: false,
      isSendLegal: false,
      isSendContact: false,
      pickerOptions:{
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      disabledHouse:false
    }
  },
  watch: {
    'form.uscCode': {
      deep: true,
      handler: function (newV, oldV) {
        if (!!newV) {
          if(this.actionType=='1'){
            this.checkXY = true;
          }else{
            this.isNeedSign(newV);
          }
        }
      }
    },
    'form.legalPerson': {
      deep: true,
      handler: function (newV, oldV) {
        if (!!newV && !!this.sameWithCorp) {
          this.form.contactsIdentificationName = newV;
        }
      }
    },
    'form.identificationNumber': {
      deep: true,
      handler: function (newV, oldV) {
        if (!!newV && !!this.sameWithCorp) {
          this.form.contactsIdentificationCard = newV;
        }
      }
    },
    'form.corporatePhone': {
      deep: true,
      handler: function (newV, oldV) {
        if (!!newV && !!this.sameWithCorp) {
          this.form.contactsIdentificationNumber = newV;
        }
      }
    },
    sameWithCorp: function (val) {
      this.form.contactsIdentificationName = !!val ? this.form.legalPerson : '';
      this.form.contactsIdentificationCard = !!val ? this.form.identificationNumber : '';
      this.form.contactsIdentificationNumber = !!val ? this.form.corporatePhone : '';
      this.clearValidate();
    },
    corporateZjType(val) {
      if (val == '0') {
        this.form.certificateExpirationDate = '99991231';
      } else {
        if (this.form.certificateExpirationDate == '99991231') {
          this.form.certificateExpirationDate = '';
        }
      }
      this.clearValidate();
    }
  },
  components: {
    top,
    upload,
    Msg,
    timerLegal,
    timerContacts,
    eSign
  },

  computed: mapState({
    user(state) {
      return state.user;
    }
  }),

  props:{
    actionType: {
      type: String
    },
    ztInfo:{
      type:Object,
      default () {
        return {
          uscCode:'',
          tenantName:''
        }
      }
    }
  },

  mounted() {
    this.disabledHouse = this.actionType=='1'?true:false;
    this.initSupplyPage();
  },
  methods: {
    //******************发送短信验证码********************
    sendMessage(phone,param) {
      let _ = this;
      sendVeriCode(phone,'verifyKyc').then(response => {
        if (response.code === 200) {
          if(param == 'disabledContacts'){
            _.isSendContact = true;
          }else{
            _.isSendLegal = true;
          }
          _.$message.success('验证码已发送！');
        }
      });
    },
    sendCode(val,param){
      if(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(val)){
        this.setDisabled(true,param); //设置按钮不可用
        this.$refs[param].start(); //启动倒计时
        this.sendMessage(val,param)
      }else{
        this.$message({
          message: '请输入正确的手机号！',
          type: 'warning'
        });
      }
    },
    setDisabled(val,param){
      this[param] = val;
    },
    /***
     * 是否需要进行签章
     * false未签章
     * true 已签章
     */
    isNeedSign(uscCode, callback){
      let _ = this;
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      isESign(uscCode).then(res=>{
        loading.close();
        if(res.code==200){
          _.checkXY = res.data;
          callback && callback()
        }
      });
    },
    closeSign() {
      this.showEsign = false;
    },
    /***
     * 页面初始化
     * 回填表单数据
     */
    initSupplyPage(){
      let _ = this;
      this.form.contactsIdentificationNumber = this.$store.state.user.user.phone;
      let uscCode = this.$store.state.user.user.uscCode;
      if(this.actionType=='1'){//修改企业信息
        queryUserKyc(uscCode).then(res=>{
          if(res.code==200){
            for(let key in _.form){
              if (key=='isProperty'){
                _.form[key] = Number(res.data[key]);
              }else{
                _.form[key] = res.data[key];
              }
            }

            _.corporateZjType = _.form.certificateExpirationDate=='99991231'?'0':'1';
            _.isCheckedOrNot();
            _.clearValidate();
          }
        });
      }else{
        if(this.ztInfo.tenantName && this.ztInfo.uscCode){
          this.form.tenantName = this.ztInfo.tenantName;
          this.form.uscCode = this.ztInfo.uscCode;
        }else{
          queryUserKyc(uscCode).then(res=> {
            if (res.code == 200) {
              _.form.tenantName = res.data.tenantName;
              _.form.uscCode = res.data.uscCode;
            }
          })
        }
      }
    },
    /***
     * 是否勾选
     * 与法人一致
     *
     */
    isCheckedOrNot(){
      if(this.form.contactsIdentificationName == this.form.legalPerson &&
          this.form.contactsIdentificationCard == this.form.identificationNumber &&
          this.form.photoVerifyCode==this.form.contactsIdentificationVerifyCode &&
          this.form.contactsIdentificationNumber == this.form.corporatePhone
      ){
        this.sameWithCorp = true;
      }else{
        this.sameWithCorp = false;
      }
    },
    clearValidate() {
      this.$refs.form.clearValidate();
    },
    hideMsg() {
      this.showMsg = false;
    },
    showBigImage(url) {
      this.showMsg = true;
      this.imageUrl = url;
    },
    handleSubmitDown() {
      let _ = this;
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!_.form.businessLicenseUrl) {
            _.$message({
              message: '请上传营业执照！',
              type: 'warning'
            });
          } else {
            _.idCardValidate();
          }
        } else {
          _.showFormError();
          return false;
        }
      });
    },
    /***
     * 表单异常
     * 非空校验
     *
     */
    showFormError() {
      let _ = this;
      setTimeout(() => {
        _.vTool.showSingleError();
      }, 30);
    },
    /***
     * 上传身份证
     * 非空校验
     *
     */
    idCardValidate() {
      let _ = this;
      if (!this.form.photoFrontUrl) {
        this.$message({
          message: '请上传身份证证件正面照片！',
          type: 'warning'
        });
      } else {
        if (!this.form.photoBackUrl) {
          this.$message({
            message: '请上传身份证证件反面照片！',
            type: 'warning'
          });
        } else {
          this.submitKycForm();
        }
      }
    },

    /***
     * sendFlag
     * 是否发送短信验证码
     * 提交KYC表单信息
     */
    submitKycForm(param) {
      if(this.actionType=='1'){
        this.formSubmit();
      }else{
        this.isNeedSign(this.form.uscCode,()=>{
          if (this.checkXY) {
            this.showEsign = false;
            this.formSubmit();
          } else {
            this.showEsign = true;
            param==1 && this.$refs['eSign'].setParam();
          }
        });
      }
    },
    formSubmit(){
      let _ = this;

      this.form.corporationStep = 'step6';

      if(this.sameWithCorp){
        this.form.contactsIdentificationVerifyCode= this.form.photoVerifyCode;
      }
      this.btnLoading = true;
      modifyUserKyc(this.form).then(response => {
        if (response.code === 200) {
          _.btnLoading = false;
          _.updateUser();
          if(_.actionType=='1'){
            _.$message.success('企业信息修改成功!');
          }else{
            _.$emit('supply-completed');
          }
        }else{
          _.btnLoading = false;
        }
      }).catch(e => {
        _.btnLoading = false;
      });

    },
    //******************更新当前用户信息********************
    updateUser(){
      let _ = this;
      updateCurrentUser(this.form.uscCode).then(response=>{
        if(response.code==200){
          _.$store.commit('LOGIN_SUCCESS',response.data);
        }
      });
    },
    //**********************文件上传************************
    yyzzFileUpload(file) {
      let _ = this;
      let formData = new FormData();
      let loadingInstance = Loading.service({
        text: '上传中...',
        fullscreen: false,
        background: 'rgba(255, 255, 255, .99)',
        target: document.getElementById('bussinessFile')
      });
      formData.append('file', file.file);
      licenseUpload(formData).then(response => {
        if (response.code === 200) {
          _.form.uscCode = response.data.uscCode;
          _.form.tenantName = response.data.companyName;
          _.form.businessLicenseUrl = response.data.url;
          _.clearValidate();
        } else {
          _.$refs.yyzzUpload.handleError();
        }
        loadingInstance.close();
      }).catch(e => {
        loadingInstance.close();
        _.$refs.yyzzUpload.handleError();
      });
    },
    cardFileUpload(file) {
      let _ = this;
      let formData = new FormData();
      let loadingInstance = Loading.service({
        text: '上传中...',
        fullscreen: false,
        background: 'rgba(255, 255, 255, .99)',
        target: document.getElementById('cardFile')
      });
      formData.append('file', file.file);
      idCardUpload(formData).then(response => {
        if (response.code === 200) {
          _.form.legalPerson = response.data.corporationName;
          _.form.identificationNumber = response.data.corporationCertNo;
          _.form.photoFrontUrl = response.data.corporationFile;
          _.clearValidate();
        } else {
          _.$refs.sfzzmUpload.handleError();
        }
        loadingInstance.close();
      }).catch(e => {
        console.log(e);
        loadingInstance.close();
        _.$refs.sfzzmUpload.handleError();
      });
    },
    cardReFileUpload(file) {
      let _ = this;
      let formData = new FormData();
      let loadingInstance = Loading.service({
        text: '上传中...',
        fullscreen: false,
        background: 'rgba(255, 255, 255, .99)',
        target: document.getElementById('cardReFile')
      });
      formData.append('file', file.file);
      idCardUploadBack(formData).then(response => {
        if (response.code === 200) {
          _.form.photoBackUrl = response.data.corporationBackFile;
          _.$set(_.form, "certificateRegistrationDate", response.data.corporationCertRegDate);
          let time_ = response.data.corporationCertExpiryDateName;
          if (time_ && time_.indexOf('长期') >= 0) {
            _.$set(_.form, "certificateExpirationDate", '99991231');
            _.corporateZjType = '0';
          } else {
            _.$set(_.form, "certificateExpirationDate", response.data.corporationCertExpiryDate);
            _.corporateZjType = '1';
          }
          _.clearValidate();
        } else {
          _.$refs.sfzfmUpload.handleError();
        }
        loadingInstance.close();
      }).catch(e => {
        loadingInstance.close();
        _.$refs.sfzfmUpload.handleError();
      });
    }
  }
}
</script>

<style lang="scss">
.sy-kyc {
  .el-radio__label {
    padding-left: 0;
  }

  .el-radio + .el-radio {
    margin-left: 0px;
  }
  .el-form-item {
    margin-bottom: 18px;
  }
  .kyc-row, .item-upload {
    width: 1048px;
    float: left;
    .tt-item {
      .el-form-item__label {
        position: absolute;
        top: -9px;
      }
    }

    margin-bottom: 10px;

    .iu-left {
      float: left;
      position: relative;

      .llt-upload {
        position: absolute;
        top: -36px;
        left: 31px;
        color: #959393;
        font-size: 12px;
      }
      .yyzz-item{
        font-size: 14px;
        margin: 0;
        text-align: center;
        color: #ffb100;
      }
    }

    .bus-title {
      float: left;
      padding-right: 12px;
      font-size: 14px;
      width: 128px;
      text-align: right;
    }

    .kyc-col {
      label.el-radio:last-child{
        position: relative;
        top: -20px;
      }
      .el-form-item__error{
        position: absolute;
        top: 42px;
        left: 30%;
      }
    }
  }

  .kyc-last{
    height: 58px;
    .is-error{
      padding-bottom: 30px;
    }
  }
  .el-radio{
    margin-right: 6px;
  }
  .main {
    float: left;
    width: 100%;
    /*margin-top: 8px;*/
    height: 100%;

    label, .item-title {
      font-weight: normal;
    }

    .kyc-form {
      width: 1200px;
      background: white;
      height: 100%;
      margin: 0 auto;

      .baseDocument {
        width: 100%;
        float: left;
      }

      .top-tips {
        font-weight: bold;
        padding: 20px;
        width: 100%;
        float: left;
        img{
          width: 4px;
          height: 15px;
          left: -4px;
          position: relative;
          top: 3px;
        }
      }

      .top-tips__ {
        font-weight: normal;
        padding: 20px;
        float: left;
        /*padding-left: 72px;*/
      }

      .top-err_tips {
        background: #FFF8ED;
        text-align: center;
        text-align: center;
        font-weight: normal;
        font-size: 14px;
        padding: 10px 0px;
        color: rgb(255, 153, 13);
        border: 1px solid #FF990D;
      }


      .select-base {
        width: 108px;
        position: absolute;
        z-index: 9999999999;
      }

      .select-province {
        left: 160px;
      }

      .select-city {
        left: 275px;
      }

      .select-area {
        left: 232px;
      }

      .kyc-row_last {
        text-align: center;
        margin: 20px auto 60px auto;
        width: 1048px;
        float: left;
        .kyc-btn {
          width: 120px;
          border-radius: 6px
        }
      }
    }
  }
}

</style>
